package com.zb.framework.controller;

import com.google.common.collect.Maps;
import com.zb.zeus.common.core.web.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Map;

/**
 * Google 验证
 *
 * @author fujianjian
 * @since 2022/3/9 11:03
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/google/check/")
@Api(value = "DEMO服务接口", tags = "DEMO服务接口")
public class GoogleCheckController {

    @GetMapping("gen/secret")
    @ApiOperation("3、生成google密钥")
    public AjaxResult generateGoogleSecret() throws Exception {
        //Google密钥
        String randomSecretKey = GoogleAuthenticator.getRandomSecretKey();
        String googleAuthenticatorBarCode = GoogleAuthenticator.getGoogleAuthenticatorBarCode(randomSecretKey,
                "付健健", "正邦科技");
        Map<String, Object> data = Maps.newHashMap();
        //Google密钥
        data.put("secret", randomSecretKey);
        //用户二维码内容
        data.put("secretQrCode", googleAuthenticatorBarCode);
        return AjaxResult.success(data);
    }

    @GetMapping("gen/qrcode")
    @ApiOperation("4、生成二维码，这个去地址栏请求，不要用Swagger-ui请求")
    public void genQrCode(String secretQrCode, HttpServletResponse response) throws Exception {
        response.setContentType("image/png");
        OutputStream stream = response.getOutputStream();
        QRCodeUtil.encode(secretQrCode, stream);
    }

    /**
     * @param code
     * @return
     */
    @GetMapping("execute")
    @ApiOperation("4、生成二维码，这个去地址栏请求，不要用Swagger-ui请求")
    public AjaxResult verifyGoogleCheck(long code) {
        String secret = "FWUKM2LZ3QKVWQHXRJL3QKTUSOAUZX6F";
        boolean ret = GoogleAuthenticator.check_code(secret, code);
        return ret ? AjaxResult.success("验证成功") : AjaxResult.error("验证失败");
    }
}
